package unionfind;

//路径压缩优化
public class UnionFind5 implements UF {
    private int parent[];
    private int rank[];


    public UnionFind5(int size) {

        parent = new int[size];
        rank = new int[size];
        for (int i = 0; i < size; i++) {
            parent[i] = i;
            rank[i] = 1;
        }


    }

    private int find(int p) {
        if (p < 0 || p >= parent.length) {
            throw new IllegalArgumentException("index is illegal");
        }

        while (p != parent[p]) {
            parent[p] = parent[parent[p]];
            p = parent[p];
        }
        return p;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void union(int p, int q) {

        int pRoot = find(p);
        int qRoot = find(q);

        if (pRoot == qRoot) {
            return;
        }

        if (rank[pRoot] < rank[qRoot]) {
            parent[p] = qRoot;

        } else if (rank[pRoot] > rank[qRoot]) {
            parent[q] = pRoot;

        } else {
            parent[p] = qRoot;
            rank[q] += 1;

        }

    }
}
